package com.platform.qujia.controller;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.platform.qujia.dao.PayOrderMapper;
import com.platform.qujia.dao.PayWayMapper;
import com.platform.qujia.dao.StationMapper;
import com.platform.qujia.pojo.*;
import com.platform.qujia.pojo.dto.BroadcastCancelOrderDTO;
import com.platform.qujia.pojo.vo.POSPayOrderVO;
import com.platform.qujia.rocketmq.SettleInfoProducer;
import com.platform.qujia.service.*;
import com.platform.qujia.utils.CodeMsg;
import com.platform.qujia.utils.DateUtils;
import com.platform.qujia.utils.ResultData;
import com.platform.qujia.utils.exception.EndingException;
import com.platform.qujia.utils.redis.RedisCacheUtil;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.util.*;

@Controller
@Slf4j
@CrossOrigin
public class PayOrderController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(PayOrderController.class);


    @Resource
    private PayOrderService payOrderService;

    @Resource
    private ClassSettlementService classSettlementService;

    @Autowired
    private RedisCacheUtil redisCacheUtil;

    @Resource
    private SettleInfoProducer settleInfoProducer;

    @Resource
    private PayOrderMapper payOrderMapper;

    @Resource
    private EnterpriseService enterpriseService;

    @Resource
    private StationMapper stationMapper;

    @Resource
    private PayWayMapper payWayMapper;
    @Autowired
    private GzhNewsTemplateService gzhNewsTemplateService;

    @RequestMapping(value = "/sendSettleInfo", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询订单列表", httpMethod = "POST", notes = "查询订单列表所用到参数：stationId(油站ID);pageNum（页码）；pageSize（页面大小）； beginTime（开始时间）；endTime（结束时间）；支付方式（非必传）")
    public String pushSettleInfo() {

        log.info("开始补送清分信息");
        List<PayOrder> payOrders = payOrderMapper.selectPayOrderListAll();

        for (PayOrder order : payOrders) {
            log.info("需要补送的订单号{}",order.getOrderNo());
            Integer stationId = order.getStationId();

            PayWay payWay = new PayWay();
            payWay.setPayWayId(order.getPayWayId());
            PayWay oneStationPayWay = payWayMapper.getOneStationPayWay(payWay);

            String merchantsNumber = order.getMerchantsNumber();
            Date payDate = order.getPayDate();
            String payTime = DateUtil.format(payDate, DatePattern.PURE_DATETIME_PATTERN);

            Station station = stationMapper.selectStationById(stationId);


            SaasOrderBo saasOrderBo = SaasOrderBo.builder()
                    .payOrder(merchantsNumber)
                    .payMerNo(oneStationPayWay.getMno())
                    .payTime(payTime)
                    .orderType("01")
                    .orderAmt(Objects.nonNull(order.getAmt()) ? BigDecimal.valueOf(order.getAmt()) : BigDecimal.ZERO)
                    .payAmt(Objects.nonNull(order.getAmt()) ? BigDecimal.valueOf(order.getAmt()) : BigDecimal.ZERO)
                    .marketingOrder("")
                    .totalDisAmt(BigDecimal.ZERO)
                    .merchantDisAmt(BigDecimal.ZERO)
                    .platformDisAmt(BigDecimal.ZERO)
                    .sponsorDisAmt(BigDecimal.ZERO)
                    .clearAccount(station.getClearAccount())
                    .clearMerNo(station.getClearMerMo())
                    .optAmt(new BigDecimal("0")).build();
            //发送消息
            settleInfoProducer.sendMessage(saasOrderBo);
        }
        return "success";
    }

    @RequestMapping(value = "/selecttest1", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询订单列表", httpMethod = "GET", notes = "查询订单列表所用到参数：stationId(油站ID);pageNum（页码）；pageSize（页面大小）； beginTime（开始时间）；endTime（结束时间）；支付方式（非必传）")
    public void test1(){
        SaasOrderBo saasOrderBo = SaasOrderBo.builder()
                .payOrder("123213123")
                .payAmt(new BigDecimal("0.01"))
                .marketingOrder("dsfadfadsf")
                .clearAccount("123456")
                .clearMerNo("123456")
                .merchantDisAmt(new BigDecimal("1.23")).build();
        settleInfoProducer.sendMessage(saasOrderBo);
        System.out.println();
    }


    /*
     * pos临时查询订单列表
     * @param stationId
     * @param userName
     * @return
     */
    @RequestMapping(value = "/selectPosPayOrdersListTmp", method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "查询订单列表", httpMethod = "POST", notes = "查询订单列表所用到参数：stationId(油站ID);pageNum（页码）；pageSize（页面大小）； beginTime（开始时间）；endTime（结束时间）；支付方式（非必传）")
    public String selectPosPayOrdersListTmp(@RequestBody PayOrder request) {
        try {
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            //返回结果集
            ResultData resultData = null;
            if (request.getStationId() == null) {
                throw new EndingException("必传参数为空~");
            }
            PayOrder payOrder = new PayOrder();
            payOrder.setStationId(request.getStationId());
            payOrder.setBeginTime(request.getBeginTime());
            payOrder.setEndTime(request.getEndTime());
            payOrder.setPayType(request.getPayType());
            payOrder.setStatus(request.getStatus());
            payOrder.setOilPersonnelId(request.getOilPersonnelId());

            Map<String, Object> resultMap = new HashMap<>();
            if (request.getPageNum() == null || request.getPageSize() == null) {
                throw new EndingException("必传参数为空~");
            }
            //分页
            PageHelper.startPage(request.getPageNum(), request.getPageSize());
            Station station = stationMapper.selectStationById(payOrder.getStationId());
            String showPayWayIds =  station.getShowPayWayIds();
            if (showPayWayIds!=null){
                String[] idArray = showPayWayIds.split(","); // 拆分成字符串数组
                List<Long> idList = new ArrayList<>();
                for (int i = 0; i < idArray.length; i++) {
                    String id = idArray[i].trim();
                    if (!id.isEmpty()) {
                        idList.add(Long.parseLong(id));
                    }
                }
                payOrder.setPayWayIdList(idList);
            }
            if(request.getUserId()!=null) {
                String isStaffUser = classSettlementService.isStaffUserBGApi(Long.parseLong(request.getUserId()));
                if (isStaffUser.equals("1")) {

                }else{
                    payOrder=   payOrderService.timeSetting(payOrder,request.getStationId());
                }
            }else{
                payOrder=   payOrderService.timeSetting(payOrder,request.getStationId());
            }
            List<POSPayOrderVO> payOrderList = payOrderService.selectPayOrderListTemp(payOrder);
            Map<String, Object> listSumList = payOrderService.selectSumTmp(payOrder);

            PageInfo pageInfo = new PageInfo(payOrderList);


            resultMap.put("orderList",pageInfo);
            resultMap.put("listSum",listSumList);

            resultData = ResultData.success(resultMap);

            return gson.toJson(resultData);
        }catch (EndingException e){
            return ResultData.errorJsonWithCode(e.getCode(),e.getMessage());
        }catch(Exception e){
            logger.error("/selectPosPayOrdersListTmp", e);
            return ResultData.errorJson(e.getMessage());
        }

    }

    @GetMapping(value = "/getCdkOrderResult/{cdkKey}")
    @ResponseBody
    @ApiOperation(value = "查询车队卡订单结果", httpMethod = "GET", notes = "key 卡号加时间戳")
    public ResultData getCdkOrderResult(@PathVariable("cdkKey") String key){
        Integer orderId=redisCacheUtil.getCacheObject(key);
        JSONObject data=new JSONObject();
        ResultData resultData = null;

        if(orderId!=null){
            PayOrder payOrder=payOrderService.searchPayOrder(orderId);
            data.put("orderId",orderId);
            if(payOrder!=null){
                data.put("orderNo",payOrder.getOrderNo());
            }
            if(payOrder.getStatus().equals("1")){
                data.put("result","HAVE_PAID");
                resultData=ResultData.success(data);
                redisCacheUtil.deleteObject(key);
            }else{
                data.put("result","NON_PAYMENT");
                resultData=ResultData.success(data);
            }
        }else{
            data.put("result","NULL");
            resultData=ResultData.success(data);
        }
        return  resultData;
    }

    @PostMapping("/dual/payOrderList")
    @ResponseBody
    public ResultData getPayOrderListByDual(@RequestBody PayOrder request){
        if(Objects.isNull(request) || StringUtils.isEmpty(request.getBeginTime())){
            Date date = new Date();
            String beginTime = DateUtils.parseDateToStr("yyyy-MM-dd HH:mm:ss", date);
            Map<String,Object> map = new HashMap<>();
            map.put("beginTime",beginTime);
            return ResultData.success(map);
        }

        if(StringUtils.isEmpty(request.getUserId())){
            return ResultData.error("没有当前用户id");
        }
        if(Objects.isNull(request.getStationId())){
            return ResultData.error("没有当前油站");
        }

        PayOrder payOrder = new PayOrder();
        payOrder.setStationId(request.getStationId());
        payOrder.setBeginTime(request.getBeginTime());
        payOrder.setStatus("1");  // 已支付的
        payOrder.setOilPersonnelId(request.getUserId());
        List<PayOrder> payOrderList = payOrderService.selectPayOrderListFormater(payOrder);
//        log.info("双屏机查询订单getPayOrderListByDual 请求参数：[{}],返回结果：[{}]",JSONObject.toJSONString(request),payOrderList.size());
        return ResultData.success(payOrderList);
    }

    @ResponseBody
    @GetMapping("payOrder/cancel/broadcast")
    public ResultData broadcastCancelOrder(@Validated(BroadcastCancelOrderDTO.GetView.class) BroadcastCancelOrderDTO cancelOrderDTO) {
        gzhNewsTemplateService.broadcastCancelOrder(cancelOrderDTO);
        return ResultData.success();
    }

    @ResponseBody
    @PostMapping("payOrder/cancel/broadcast")
    public ResultData broadcastCancelOrderPost(@RequestBody @Validated(BroadcastCancelOrderDTO.PostView.class) BroadcastCancelOrderDTO cancelOrderDTO) {
        gzhNewsTemplateService.broadcastCancelOrder(cancelOrderDTO);
        return ResultData.success();
    }

}
